<template>
  <div class="app-container">
    <el-form>
      <el-form-item label="命名方式">
        <el-select v-model="goodsGalleryMethod" placeholder="命名方式" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.goods_gallery_method" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>

        <el-upload class="upload-demo" drag action="#" multiple ref="upload" :file-list="files"
          :http-request="handleUpload" :on-exceed='handExceed' :on-remove="handleRemove"
          :on-success='handFileSuccess' :before-remove="beforeRemove" :auto-upload="false"
          :limit="100">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">一次只能上传100个文件</div>
        </el-upload>
        <div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="CancelUpload">取 消</el-button>
            <el-button type="primary" @click="fileChange">立即上传</el-button>
          </span>
        </div>
      </el-form-item>
    </el-form>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="20%">
      <span>上传失败{{dialogVisibleContext}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import axios from 'axios';

export default {
  name: "GoodsGallery",
  dicts: ['goods_gallery_method'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 查询参数
      goodsGalleryMethod: 'IDENTIFIER',
      // 表单校验
      rules: {
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      headers: {
        Authorization: "Bearer " + getToken(),
        "Content-Type": "multipart/form-data"
      },
      files: [],
      dialogVisible: false,
      dialogVisibleContext: '',
    };
  },
  created () {
  },
  methods: {
    handleUpload (raw) {
      this.files.push(raw.file);
    },
    async fileChange () {
      if (this.goodsGalleryMethod == '') {
        this.$message.warning(`请选择文件命名方式`);
        return
      }
      if (this.files.length > 20) {
        this.$message.warning(`当前限制只能上传选择 1~20 个文件`);
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$refs.upload.submit() // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
      let formData = new FormData();
      formData.append("random", Math.random());
      this.files.forEach(function (file) {
        formData.append('file', file); // 因为要上传多个文件，所以需要遍历一下才行
        // 不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      })
      let res = await axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/sku/${this.goodsGalleryMethod}/upload`, formData, { headers: this.headers });
      if (res.data.code == 200) {
        this.$refs.upload.clearFiles();
        this.files = []
        let objList = []
        this.$modal.msgSuccess("上传成功")

        this.CancelUpload()
      } else {
        // this.$message.error("上传文件失败" + res.data.msg);
        // this.$modal.confirm("上传文件失败" + res.data.msg)
        this.dialogVisibleContext = res.data.msg
        this.dialogVisible = true
        this.CancelUpload()
      }
      loading.close();
    },
    handExceed (files, fileList) {
      this.$message.warning(`当前限制选择 100 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    CancelUpload () {
      this.files = []
      this.$refs.upload.clearFiles();
    },
    handFileSuccess (file) {
      console.log(file);
      this.files = []
      this.$refs.upload.clearFiles();
    },
    handleRemove (file, fileList) {
      // console.log(file, fileList);
      this.files = fileList
    },
    beforeRemove (file, fileList) {
      // console.log(file, fileList);
    },
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  width: 23%;
}
</style>
